/**
 * 简化版评分控制器
 * 实现异步队列架构，解决net::ERR_CONNECTION_RESET问题
 * 使用CommonJS格式，兼容现有系统
 */

const db = require('../config/database');
const { generatePatientCode } = require('../utils/crypto');
const simpleQueueConfig = require('../config/simpleQueueConfig');
const path = require('path');
const fs = require('fs').promises;

// 生成任务ID
function generateTaskId() {
  return 'task_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}

// 提交评分任务 - 异步队列版本
async function submitTask(req, res) {
  let connection;
  try {
    // 添加安全检查，确保req.user存在
    if (!req.user || !req.user.doctor_id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证或认证信息无效',
        data: null
      });
    }

    const { patient_code, clinical_text } = req.body;
    const { doctor_id } = req.user;
    const imageFile = req.file;

    // 参数验证
    if (!imageFile) {
      return res.status(400).json({
        success: false,
        message: '请上传内镜图像',
        data: null
      });
    }

    if (!patient_code || !patient_code.trim()) {
      return res.status(400).json({
        success: false,
        message: '患者编号不能为空',
        data: null
      });
    }

    console.log('📤 提交评分任务:', {
      doctor_id,
      patient_code,
      clinical_text: clinical_text?.substring(0, 100),
      image_filename: imageFile.filename,
      image_size: imageFile.size
    });

    // 生成任务ID
    const taskId = generateTaskId();

    // 使用事务处理
    const result = await db.transaction(async (conn) => {
      // 1. 查找或创建患者
      const patients = await conn.query(
        'SELECT patient_id FROM patients WHERE patient_code = ?',
        [patient_code.trim()]
      );

      let patient_id;
      if (patients.length === 0) {
        // 创建新患者
        const insertResult = await conn.query(
          'INSERT INTO patients (patient_code) VALUES (?)',
          [patient_code.trim()]
        );
        patient_id = insertResult[0]?.insertId;
        console.log('✅ 创建新患者:', { patient_id, patient_code: patient_code.trim() });
      } else {
        patient_id = patients[0].patient_id;
        console.log('✅ 使用现有患者:', { patient_id, patient_code: patient_code.trim() });
      }

      // 2. 创建评分任务（状态设置为"分析中"）
      const taskResult = await conn.query(`
        INSERT INTO scoring_tasks (task_id, patient_id, doctor_id, status, submit_time, image_url, clinical_text)
        VALUES (?, ?, ?, 2, datetime('now'), ?, ?)
      `, [
        taskId,
        patient_id,
        doctor_id,
        `/uploads/medical_images/${imageFile.filename}`,
        clinical_text || null
      ]);

      const dbTaskId = taskResult[0]?.insertId;

      console.log('✅ 评分任务创建成功:', {
        task_id: taskId,
        db_task_id: dbTaskId,
        patient_id,
        doctor_id
      });

      return {
        taskId,
        dbTaskId,
        patient_id,
        imagePath: `/uploads/medical_images/${imageFile.filename}`
      };
    });

    // 3. 尝试添加到AI推理队列
    let queuedSuccessfully = false;
    try {
      // 检查Redis是否可用
      const redisAvailable = await simpleQueueConfig.checkRedisAvailability();

      if (redisAvailable) {
        // 准备队列任务数据
        const queueTaskData = {
          taskId: result.taskId,
          dbTaskId: result.dbTaskId,
          imagePath: result.imagePath,
          taskData: {
            taskId: result.taskId,
            patientId: result.patient_id,
            doctorId: doctor_id,
            patientCode: patient_code.trim(),
            clinicalText: clinical_text || null,
            imagePath: result.imagePath,
            createdAt: Date.now()
          }
        };

        // 添加到队列
        const job = await simpleQueueConfig.addAIInferenceTask(queueTaskData, {
          priority: 0,
          attempts: 2,
          delay: 0
        });

        console.log(`✅ AI推理任务已添加到队列: ${job.id}`);
        queuedSuccessfully = true;

      } else {
        console.warn('⚠️ Redis不可用，跳过队列，任务将标记为待处理');
      }

    } catch (queueError) {
      console.error('❌ 添加AI推理任务到队列失败:', queueError);
      // 队列失败不影响主流程，继续返回响应
    }

    // 4. 立即返回202 Accepted响应 - 无论队列是否成功
    res.status(202).json({
      success: true,
      message: queuedSuccessfully ? '任务已提交，正在进行分析中...' : '任务已提交，将在后台处理',
      data: {
        task_id: result.taskId,
        db_task_id: result.dbTaskId,
        status: 2, // 分析中
        message: queuedSuccessfully ?
          'AI分析正在进行中，请稍后查看结果' :
          '任务已接收，将在后台处理',
        patient_code: patient_code.trim(),
        image_path: result.imagePath,
        queued_successfully: queuedSuccessfully,
        estimated_processing_time: '30-60秒'
      }
    });

    console.log(`✅ 任务提交响应已返回: ${result.taskId}, 队列状态: ${queuedSuccessfully ? '成功' : '跳过'}`);

  } catch (error) {
    console.error('❌ 提交评分任务失败:', error);
    res.status(500).json({
      success: false,
      message: '任务提交失败，请稍后重试',
      data: null
    });
  }
}

// 获取任务状态 - 支持轮询
async function getTaskStatus(req, res) {
  try {
    // 添加安全检查，确保req.user存在
    if (!req.user || !req.user.doctor_id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证或认证信息无效',
        data: null
      });
    }

    const { task_id } = req.body;
    const { doctor_id, role } = req.user;

    if (!task_id) {
      return res.status(400).json({
        success: false,
        message: '任务ID不能为空',
        data: null
      });
    }

    // 查询任务状态
    const tasks = await db.query(`
      SELECT
        st.task_id,
        st.patient_id,
        st.doctor_id,
        st.status,
        st.submit_time,
        st.complete_time,
        st.error_message,
        p.patient_code,
        d.real_name as doctor_name,
        sr.score,
        sr.severity,
        sr.confidence,
        sr.analysis_details
      FROM scoring_tasks st
      LEFT JOIN patients p ON st.patient_id = p.patient_id
      LEFT JOIN doctors d ON st.doctor_id = d.doctor_id
      LEFT JOIN scoring_results sr ON st.task_id = sr.task_id
      WHERE st.task_id = ?
      ${role !== 3 ? 'AND st.doctor_id = ?' : ''}
    `, role !== 3 ? [task_id, doctor_id] : [task_id]);

    if (!tasks || tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在或无权访问',
        data: null
      });
    }

    const task = tasks[0];

    // 检查队列状态（如果Redis可用）
    let queueStatus = null;
    try {
      const redisAvailable = await simpleQueueConfig.checkRedisAvailability();
      if (redisAvailable && task.status === 2) { // 分析中状态
        // 这里可以根据job id检查队列状态
        // queueStatus = await simpleQueueConfig.getJobStatus(jobId);
      }
    } catch (error) {
      console.error('检查队列状态失败:', error);
    }

    const response = {
      task_id: task.task_id,
      status: task.status,
      status_name: getStatusName(task.status),
      submit_time: task.submit_time,
      complete_time: task.complete_time,
      patient_code: task.patient_code,
      doctor_name: task.doctor_name,
      error_message: task.error_message,
      queue_status: queueStatus,
      ai_result: task.score ? {
        score: task.score,
        severity: task.severity,
        severity_name: getSeverityName(task.severity),
        confidence: task.confidence,
        analysis_details: task.analysis_details
      } : null
    };

    res.json({
      success: true,
      message: '获取任务状态成功',
      data: response
    });

  } catch (error) {
    console.error('❌ 获取任务状态失败:', error);
    res.status(500).json({
      success: false,
      message: '获取任务状态失败',
      data: null
    });
  }
}

// 获取评分任务列表
async function getTaskList(req, res) {
  try {
    // 添加安全检查，确保req.user存在
    if (!req.user || !req.user.doctor_id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证或认证信息无效',
        data: null
      });
    }

    const { page = 1, pageSize = 10, patient_code, status } = req.body;
    const { doctor_id, role } = req.user;

    const offset = (page - 1) * pageSize;

    // 构建查询条件
    let whereConditions = [];
    let queryParams = [];

    console.log(`[getTaskList] 查询参数:`, { page, pageSize, patient_code, status, doctor_id, role });

    // 非系统管理员只能查看自己提交的任务
    if (role !== 3) {
      whereConditions.push('st.doctor_id = ?');
      queryParams.push(doctor_id);
    }

    if (patient_code && patient_code.trim()) {
      whereConditions.push('p.patient_code LIKE ?');
      queryParams.push(`%${patient_code.trim()}%`);
    }

    if (status !== undefined && status !== null && status !== '') {
      whereConditions.push('st.status = ?');
      queryParams.push(parseInt(status));
    }

    const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';

    // 查询任务列表
    const [tasks] = await db.query(`
      SELECT
        st.task_id,
        st.patient_id,
        st.doctor_id,
        st.status,
        st.submit_time,
        st.complete_time,
        st.error_message,
        p.patient_code,
        d.real_name as doctor_name,
        d.department,
        sr.score,
        sr.severity,
        sr.confidence,
        sr.analysis_details
      FROM scoring_tasks st
      LEFT JOIN patients p ON st.patient_id = p.patient_id
      LEFT JOIN doctors d ON st.doctor_id = d.doctor_id
      LEFT JOIN scoring_results sr ON st.task_id = sr.task_id
      ${whereClause}
      ORDER BY st.submit_time DESC
      LIMIT ? OFFSET ?
    `, [...queryParams, parseInt(pageSize), offset]);

    // 查询总数
    const [countResult] = await db.query(`
      SELECT COUNT(*) as total
      FROM scoring_tasks st
      LEFT JOIN patients p ON st.patient_id = p.patient_id
      ${whereClause}
    `, queryParams);

    const total = countResult?.[0]?.total || 0;

    // 格式化任务数据
    const formattedTasks = (tasks || []).map(task => ({
      task_id: task.task_id,
      patient_code: task.patient_code,
      doctor_name: task.doctor_name,
      department: task.department,
      status: task.status,
      status_name: getStatusName(task.status),
      submit_time: task.submit_time,
      complete_time: task.complete_time,
      error_message: task.error_message,
      score: task.score,
      severity: task.severity,
      severity_name: getSeverityName(task.severity),
      confidence: task.confidence,
      analysis_details: task.analysis_details
    }));

    res.json({
      success: true,
      message: '获取任务列表成功',
      data: {
        items: formattedTasks,
        pagination: {
          current_page: parseInt(page),
          page_size: parseInt(pageSize),
          total: total,
          total_pages: Math.ceil(total / pageSize)
        }
      }
    });

  } catch (error) {
    console.error('❌ 获取任务列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取任务列表失败',
      data: null
    });
  }
}

// 获取单个评分结果
async function getTaskResult(req, res) {
  try {
    // 添加安全检查，确保req.user存在
    if (!req.user || !req.user.doctor_id) {
      return res.status(401).json({
        success: false,
        message: '用户未认证或认证信息无效',
        data: null
      });
    }

    // 支持POST（从body获取）和GET（从params获取）两种方式
    const task_id = req.body.task_id || req.params.taskId || req.params.task_id;
    const { doctor_id, role } = req.user;

    if (!task_id) {
      return res.status(400).json({
        success: false,
        message: '任务ID不能为空',
        data: null
      });
    }

    // 查询任务详情和结果
    const queryResult = await db.query(`
      SELECT
        st.task_id,
        st.patient_id,
        st.doctor_id,
        st.status,
        st.submit_time,
        st.complete_time,
        st.image_url,
        st.clinical_text,
        st.error_message,
        p.patient_code,
        p.gender,
        p.birthday,
        d.real_name as doctor_name,
        d.department,
        d.title,
        sr.score,
        sr.severity,
        sr.confidence,
        sr.model_version,
        sr.analysis_details,
        sr.reviewed_score,
        sr.reviewed_notes
      FROM scoring_tasks st
      LEFT JOIN patients p ON st.patient_id = p.patient_id
      LEFT JOIN doctors d ON st.doctor_id = d.doctor_id
      LEFT JOIN scoring_results sr ON st.task_id = sr.task_id
      WHERE st.task_id = ?
      ${role !== 3 ? 'AND st.doctor_id = ?' : ''}
    `, role !== 3 ? [task_id, doctor_id] : [task_id]);

    const tasks = queryResult || [];

    if (tasks.length === 0) {
      return res.status(404).json({
        success: false,
        message: '任务不存在或无权访问',
        data: null
      });
    }

    const task = tasks[0];

    // 格式化返回数据
    const result = {
      task_id: task.task_id,
      patient: {
        patient_id: task.patient_id,
        patient_code: task.patient_code,
        gender: task.gender,
        gender_name: getGenderName(task.gender),
        birthday: task.birthday
      },
      doctor: {
        doctor_id: task.doctor_id,
        real_name: task.doctor_name,
        department: task.department,
        title: task.title
      },
      task_info: {
        status: task.status,
        status_name: getStatusName(task.status),
        submit_time: task.submit_time,
        complete_time: task.complete_time,
        image_url: task.image_url,
        clinical_text: task.clinical_text,
        error_message: task.error_message
      },
      ai_result: task.score ? {
        score: task.score,
        severity: task.severity,
        severity_name: getSeverityName(task.severity),
        confidence: task.confidence,
        model_version: task.model_version,
        analysis_details: task.analysis_details
      } : null,
      review_result: task.reviewed_score ? {
        reviewed_score: task.reviewed_score,
        reviewed_notes: task.reviewed_notes
      } : null
    };

    res.json({
      success: true,
      message: '获取任务结果成功',
      data: result
    });

  } catch (error) {
    console.error('❌ 获取任务结果失败:', error);
    res.status(500).json({
      success: false,
      message: '获取任务结果失败',
      data: null
    });
  }
}

// 获取队列统计信息
async function getQueueStats(req, res) {
  try {
    const stats = await simpleQueueConfig.getQueueStats();

    res.json({
      success: true,
      message: '获取队列统计成功',
      data: stats
    });

  } catch (error) {
    console.error('❌ 获取队列统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取队列统计失败',
      data: null
    });
  }
}

// 辅助函数
function getStatusName(status) {
  const statusMap = {
    1: '待处理',
    2: '分析中',
    3: '已完成',
    4: '失败'
  };
  return statusMap[status] || '未知';
}

function getSeverityName(severity) {
  const severityMap = {
    1: '缓解期',
    2: '轻度',
    3: '中度',
    4: '重度'
  };
  return severityMap[severity] || '未知';
}

function getGenderName(gender) {
  const genderMap = {
    0: '未知',
    1: '男',
    2: '女'
  };
  return genderMap[gender] || '未知';
}

module.exports = {
  submitTask,
  getTaskStatus,
  getTaskList,
  getTaskResult,
  getQueueStats
};